home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 5341 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.5 KB  |  56 lines

  1. Path: news1.h1.usa.pipeline.com!usenet
  2. From: grantp@usa.pipeline.com
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Trouble w/ random numbers...please help
  5. Date: 3 Feb 1996 23:35:39 GMT
  6. Organization: Kalevi, Inc.
  7. Message-ID: <4f0rgb$4h7@news1.usa.pipeline.com>
  8. References: <4f0p3f$lon@netnews.upenn.edu>
  9. NNTP-Posting-Host: 38.8.61.12
  10. X-PipeUser: grantp
  11. X-PipeHub: usa.pipeline.com
  12. X-PipeGCOS: (Pete)
  13. X-Newsreader: Pipeline USA v3.3.0
  14.  
  15. On Feb 03, 1996 22:54:39 in article <Re: Trouble w/ random numbers...please
  16. help>, 'modavis@ssc.sas.upenn.edu (Morris A. Davis)' wrote: 
  17.  
  18.  
  19. >Daniel Cotter (cotter@www.cns.uky.edu) wrote: 
  20. >: I'm trying to write a program that will generate a set of 
  21. >: random numbers between 3 and 18. I have several problems with 
  22. >: this program. 
  23. >: 1. C++ always generates same number(346) 
  24. >can't help ya 
  25. >: 2. I don't know how to give a range. I've tried 3-18, but 
  26. >:    it thinks I mean to subtract(3-18=15) 
  27. >1. Generate a random number between 0 and 1 
  28. >2. Multiply by 15 
  29. >3. Add 3 
  30. Here's a more helpful response: 
  31. First, I assume you mean values 3 - 18 inclusive. 
  32.  
  33. #include <stdlib.h> 
  34. #include <time.h> 
  35.  
  36.  /*  In the beginning of your program, initialize the random number 
  37.      generator - lest you'll always get the same series */ 
  38.  
  39.    srand( (unsigned)time( NULL ) ); 
  40.  
  41.  /*  then, anywhere in your program you can do something  
  42.     along these lines: */ 
  43.    
  44.     int rn = rand() % 16 + 3; 
  45.  
  46.  /* rn will now contain a pseudo random value 3-18. */ 
  47.  
  48. -- 
  49. Pete Grant 
  50. Kalevi, Inc. 
  51. Object Oriented Software Development
  52.